package cn.com.clearcloud.order.service.impl;


import cn.com.clearcloud.order.client.StoreClient;
import cn.com.clearcloud.order.client.UserClient;
import cn.com.clearcloud.order.mapper.OrderMapper;
import cn.com.clearcloud.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    private final UserClient userClient;

    private final StoreClient storeClient;

    /**
     * 特别注意：不能对异常进行 try catch,会造成分布式事务失败
     *  若需要的话，则在 catch中使用 GlobalTransactional的 rollback
     * @param userId
     * @param commodityCode
     * @param orderCount
     * @return
     */
    @Override
    @GlobalTransactional
    public Boolean create(String userId, String commodityCode, Integer orderCount) {
        if(storeClient.deduct("2001",1) <0) {
            System.out.println("store service熔断");
            return Boolean.FALSE;
        }
        if (userClient.debit(userId, 5, 21) < 0) {
            System.out.println("user service熔断");
            return Boolean.FALSE;
        }
        //int i = 1/0;
        return orderMapper.create(userId,commodityCode,orderCount) > 0 ? Boolean.TRUE:Boolean.FALSE;
    }




}
